package com.atguigu.dga.governance.assess.demo;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.Collectors;

public class ThreadDemo {

   static ThreadPoolExecutor threadPoolExecutor=new ThreadPoolExecutor(100,100,60, TimeUnit.SECONDS,new LinkedBlockingDeque<>());
    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();

        Integer[] nums = {1, 2, 3, 4, 5};
/*
        Integer sum = 0;
        for (Integer num : nums) {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            sum += (num * num);
        }*/

        ArrayList<CompletableFuture<Integer>> completableFutures = new ArrayList<>();

        for (Integer num : nums) {
            //异步执行
            CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(new Supplier<Integer>() {
                @Override
                public Integer get() {
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    return num * num;
                }
            },threadPoolExecutor);
            //将封装后的每个计算的结果收集起来
            completableFutures.add(integerCompletableFuture);
        }


        //将计算结果获取到并集合在一起
        List<Integer> integers = completableFutures.stream().map(integerCompletableFuture -> integerCompletableFuture.join()).collect(Collectors.toList());

        //统一做累加
        Integer sum = 0;
        for (Integer integer : integers) {
            sum += integer;
        }


        System.out.println(sum);
        System.out.println(System.currentTimeMillis()-startTime);
    }
}
